<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;
use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 金山
 */
class JinshanController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);
        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        $data = array();
        $data['merchant_no'] = $this->config['mch_id'];
        $data['nonce_str'] = md5(date("Y-m-d H:i:s",time()) . mt_rand(10000,99999));
        $data['request_no'] = $return['orderid'];
        $data['amount'] = $return['amount'];

        $ismobile = isMobile();
        switch($product['paytype']){
            //微信
            case 1:
                $data['pay_channel'] = 'WXP';
                break;
            //微信H5
            case 2:
                $data['pay_channel'] = 'WXH5';
                break;
            //支付宝扫码
            case 3:
                $data['pay_channel'] = 'ALH5';
                break;
            //支付宝H5
            case 4:
                $data['pay_channel'] = 'ALH5';
                break;
            //支付宝扫码-2
            case 17:
                $data['pay_channel'] = 'ALH5';
                break;
            //支付宝H5-2
            case 18:
                $data['pay_channel'] = 'ALH5';
                break;
            //网银直连
            case 6:
                $data['pay_channel'] = 'WYP';
                $data['cardtype'] = '01';
                $data['clienttype'] = 1;
                switch($product['code']){
                    case 'BOB':
                        $data['bankname'] = 'BOB';
                        break;
                    case 'BEA':
                        $data['bankname'] = 'BEA';
                        break;
                    case 'ICBC':
                        $data['bankname'] = 'ICBC';
                        break;
                    case 'CEB':
                        $data['bankname'] = 'CEB';
                        break;
                    case 'CGB':
                        $data['bankname'] = 'CGB';
                        break;
                    case 'HXB':
                        $data['bankname'] = 'HXB';
                        break;
                    case 'CCB':
                        $data['bankname'] = 'CCB';
                        break;
                    case 'BOCOM':
                        $data['bankname'] = 'BOCOM';
                        break;
                    case 'CMBC':
                        $data['bankname'] = 'CMBC';
                        break;
                    case 'NJCB':
                        $data['bankname'] = 'NJCB';
                        break;
                    //宁波银行
                    case 'NBCB':
                        $data['bankname'] = '';
                        break;
                    case 'ABC':
                        $data['bankname'] = 'ABC';
                        break;
                    case 'PAB':
                        $data['bankname'] = 'PAB';
                        break;
                    //上海银行
                    case 'SHB':
                        $data['bankname'] = '';
                        break;
                    case 'SPDB':
                        $data['bankname'] = 'SPDB';
                        break;
                    //深圳发展银行
                    case 'SDB':
                        $data['bankname'] = '';
                        break;
                    case 'CIB':
                        $data['bankname'] = 'CIB';
                        break;
                    case 'PSBS':
                        $data['bankname'] = 'PSBC';
                        break;
                    case 'CMB':
                        $data['bankname'] = 'CMB';
                        break;
                    //浙商银行
                    case 'CZB':
                        $data['bankname'] = '';
                        break;
                    case 'BOC':
                        $data['bankname'] = 'BOC';
                        break;
                    case 'CTTIC':
                        $data['bankname'] = 'CITIC';
                        break;
                    default:
                        $this->showmessage('暂不支持此银行卡!',['code'=>C("THIRDCODES.".$this->class)]);
                }
                break;
            //QQ钱包扫码
            case 8:
                $data['pay_channel'] = 'QQP';
                break;
            //京东钱包
            case 9:
                $data['pay_channel'] = 'JDP';
                break;
            //银联扫码
            case 11:
                $data['pay_channel'] = 'YLP';
                break;
            //快捷支付
            case 13:
                $data['pay_channel'] = 'KJP';
                break;
            //京东H5
            case 14:
                $data['pay_channel'] = 'JDH5';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);

        }
        $data['request_time'] = time();
        //$data['account_type'] = 1;
        $data['notify_url'] = $return['notifyurl'];
        $data['goods_name'] = 'zf';
        $data['ip_addr'] = getIP();
        $data['return_url'] = $return['callbackurl'];


        ksort($data);
        $str = arrToUrlStr($data)."&key=".$this->config['signkey'];
        $data['sign'] = strtoupper(md5($str));
        $apiurl = $this->config['gateway'];

        $res = curl($apiurl, arrToUrlStr($data));

        //echo $res."<br/>";
        //保存请求返回
        M("Order")->where([ 'pay_orderid'=>$return['orderid']])->save(["rd_return"=>$res]);

        $res_arr = json_decode($res, true);


        //echo '<pre/>'; print_r($res_arr); exit;
        if($res_arr && !empty($res_arr) && $res_arr['success']!=1){
            if(isset($res_arr['data']['message'])){
                $this->showmessage($res_arr['data']['message'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage("获取的数据格式错误",['code'=>C("THIRDCODES.".$this->class)]);
        }
        /*
         * Array
            (
                [success] => 1
                [data] => Array
                    (
                        [bank_url] => weixin://wxpay/bizpayurl?pr=axt4j6g
                        [status] => 2
                        [order_no] => JYB0B668D57F010E1C48BC400344E4
                        [order_time] => 1530168413
                        [remark] => 下单成功
                        [amount] => 2
                        [nonce_str] => N25b34845e4f378
                        [sign] => BA70795C7FCC0957C765AC268B46DF6B
                    )

            )
         */

        $qrcode = $res_arr['data']['bank_url'];

        //echo '<pre/>'; print_r($res); exit;
        if(!$qrcode){
            $this->showmessage('获取二维码失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        //网银
        if( $data['pay_channel'] == 'WYP' ){
            header("Location: {$qrcode}");exit;
        }

        if(isMobile() && in_array($this->config['paytype'], array(2,4,13,14))){
            //header("Location: {$qrcode}");exit;
        }

        //返回json
        if($_REQUEST['pay_returntype']){
            $this->showJson('',$qrcode);
        }

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $qrcode);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?data=".$qrcode);

        switch($this->config['paytype']){
            //微信
            case 1:
                $this->display("WeiXin/weixin");
                break;
            //支付宝扫码
            case 3:
            case 4:
            case 17:
            case 18:
                if(isMobile()){
                    $this->display("WeiXin/alipaywap");
                }else{
                    $this->display("WeiXin/alipay");
                }
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt", "\r\n\r\n\r\n\r\n".var_export($_REQUEST, true) . "\r\n\r\n");
        //file_put_contents("a.txt", var_export($_POST, true) . "\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", var_export($_GET, true) . "\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input') . "\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date("Y-m-d H:i:s", time()) . "\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt",  "-------------------------------", FILE_APPEND);

        $p = file_get_contents('php://input');
        //$p = '{"success":true,"data":{"status":"3","request_no":"201810231922507051466","request_time":"1540293770","order_no":"1540293750200","pay_time":"1540293768","amount":"10.00","merchant_no":"JSP1800696","pay_channel":"ALH5","nonce_str":"5bcf0488d4e41","call_nums":"1","sign":"3727E3AABC3D17354406D39D9904D916"}}';

        if(!$p){
            exit("");
        }

        $arr = json_decode($p, true);

        if(empty($arr)){
            exit("");
        }

        //获取订单信息
        $orderid = $arr['data']['request_no'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "server_return"=> $p,
            "pay_orderid_rd"=>$arr['data']['order_no']
        ));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>'Jinshan'))->find();


        if($arr['success'] != 1 || $arr['data']['sign']==''){
            exit("fail");
        }

        if($arr['data']['status'] != 3){
            exit("pay_fail");
        }

        //echo '<pre/>'; print_r($p);
        if(!$p || empty($p)){
            exit("wrong");
        }

        $sign = $arr['data']['sign'];

        $brr = $arr['data'];
        unset($brr['sign']);

        ksort($brr);
        $str = arrToUrlStr($brr)."&key=".$this->config['signkey'];


        $sign2 = strtoupper(md5($str));
        if($sign != $sign2){
            echo 'sign_wrong';exit;
        }

        //处理支付
        //$this->EditMoney($find['pay_orderid'],"Jinshan",0);

        //回调成功
        //echo 'SUCCESS'; exit;
        $this->async($find['pay_orderid'],'SUCCESS');
    }

    public function callBackUrl(){

        echo '操作成功'; exit;
    }
}